<?php

declare(strict_types=1);

/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

use Hyperf\Context\ApplicationContext;
use Hyperf\HttpServer\Contract\RequestInterface;

if (!function_exists('success')) {
    function success($data = null, $extra = new stdClass()): array
    {
        return [
            'code' => 200,
            'data' => $data,
            'extra' => (object)$extra,
            'message' => 'success',
        ];
    }
}

if (!function_exists('fail')) {
    function fail($code, $message = '', $data = null, $extra = new stdClass()): array
    {
        return [
            'code' => $code,
            'message' => $message,
            'data' => $data,
            'extra' => (object)$extra,
        ];
    }
}

if (!function_exists('getClientIp')) {
    function getClientIp(): string
    {
        try {
            $request = ApplicationContext::getContainer()->get(RequestInterface::class);
            $headers = $request->getHeaders();
            if (!empty($headers['x-real-ip'][0])) {
                return $headers['x-real-ip'][0];
            }
            if (!empty($headers['x-forwarded-for'][0])) {
                $ips = explode(',', $headers['x-forwarded-for'][0]);
                $ips = array_map('trim', $ips);
                return end($ips);
            }
            if (isset($headers['http_x_forwarded_for'])) {
                // 部分CDN会获取多层代理IP，所以转成数组取第一个值
                $ips = explode(',', $headers['http_x_forwarded_for'][0]);
                $ips = array_map('trim', $ips);
                return $ips[0];
            }
            $serverParams = $request->getServerParams();
            return $serverParams['remote_addr'] ?? '127.0.0.1';
        } catch (Throwable $e) {
            logInfo('getClientIp', $e->getMessage());
            return '172.21.0.1';
        }

        /*
         * nginx 配置
         * location / {
         * # proxy host and ip information
         * proxy_set_header Host $http_host;
         * proxy_set_header X-Real-IP $remote_addr;
         * proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
         *
         * # proxy
         * proxy_pass http://127.0.0.1:9501;
         * }
         */
    }
}

if (!function_exists('json2array')) {
    /**
     * Note - json转数组
     * DateTime 2024/9/27 11:06
     * User Admin.
     * @param mixed $json_str
     * @return array
     */
    function json2array($json_str)
    {
        // 检查是否已经是数组或对象
        if (is_array($json_str) || is_object($json_str)) {
            return (array)$json_str;
        }
        // 尝试将字符串转换为数组
        $decoded = json_decode($json_str, true);
        if (json_last_error() === JSON_ERROR_NONE) {
            return json2array($decoded); // 递归处理解码后的数据
        }
        return [];
    }
}

if (!function_exists('logInfo')) {
    /**
     * Note - 记录日志
     * DateTime 2024/8/7 16:39
     * User Admin.
     * @param string $fileName 不带后缀的文件名
     * @param array $content 日志内容
     * @param string $label 日志标签
     * @return bool
     */
    function logInfo($fileName, mixed $content = 'tamgo', string $label = '')
    {
        if (is_string($content)) {
            $content = 'string [' . date('Y-m-d H:i:s') . '] ' . $label . ' ' . $content . PHP_EOL;
        } else {
            $content = gettype($content) . '[' . date('Y-m-d H:i:s') . '] ' . $label . ' ' . json_encode($content, JSON_UNESCAPED_UNICODE) . PHP_EOL;
        }
        $filePath = BASE_PATH . '/runtime/logs/' . date('Ymd') . '/' . $fileName . '.log';
        $dirPath = dirname($filePath);
        if (!file_exists($dirPath)) {
            mkdir($dirPath, 0755, true); // 0755 表示权限，true 表示递归创建
        }
        // 写入日志
        $result = file_put_contents($filePath, $content, FILE_APPEND);

        return $result !== false;
    }
}

if (!function_exists('replaceImage')) {
    function replaceImage($url)
    {
        if (is_null($url)){
            $default_article_cover = \Hyperf\Config\config('default_article_cover', '');
            $default_article_cover = explode(',', $default_article_cover);
            shuffle($default_article_cover);
            return $default_article_cover[0];
        }
        $need_replace_domain_url = \Hyperf\Config\config('replace_domain_url', '');
        $need_replace_domain_url = explode(',', $need_replace_domain_url);
        $default = \Hyperf\Config\config('file.default', '');
        $domain_url = \Hyperf\Config\config('file.storage.' . $default . '.domain_url', '');
        // 替换图片域名和端口地址
        $parsedUrl = parse_url($url);

        $scheme = $parsedUrl['scheme'] ?? '';
        $host = $parsedUrl['host'] ?? '';
        $port = $parsedUrl['port'] ?? '';
        $old_domain_url = '';
        if ($scheme) {
            $old_domain_url .= $scheme . '://';
        }
        if ($host) {
            $old_domain_url .= $host;
        }
        if ($port) {
            $old_domain_url .= ':' . $port;
        }
        if ($old_domain_url && in_array($old_domain_url, $need_replace_domain_url)){
            return str_replace($old_domain_url .'/', $domain_url, $url);
        }
        return $url;

    }
}
